#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) JoinQuant Development Team
# Author: Huayong Kuang <kuanghuayong@joinquant.com>

import os
import time
import timeit
import SharedArray

_cache  = {}
shm_path = "/dev/shm/daydata/01/000001.XSHG"


def test_attatch():
    sa = SharedArray.attach("file://" + shm_path, readonly=True)
    # print(type(sa))
    return sa


def test_cache_attatch():
    if shm_path in _cache:
        sa = _cache[shm_path]
    else:
        sa = SharedArray.attach("file://" + shm_path, readonly=True)
        _cache[shm_path] = sa
    # print(type(sa))
    return sa


def test_stat_attatch():
    ctime = os.stat(shm_path).st_ctime
    if time.time() - ctime > 10 and shm_path in _cache:
        sa = _cache[shm_path]
    else:
        sa = SharedArray.attach("file://" + shm_path, readonly=True)
        _cache[shm_path] = sa
    # print(type(sa))
    return sa


def main():
    global _cache
    print("cache len:", len(_cache))
    it = timeit.timeit(
        "test_attatch()",
        "from __main__ import test_attatch",
        number=100000
    )
    _cache = {}
    print("test_attatch take:", it)
    print("cache len:", len(_cache))
    it2 = timeit.timeit(
        "test_cache_attatch()",
        "from __main__ import test_cache_attatch",
        number=100000
    )
    print("test_cache_attatch take:", it2)
    print("cache len:", len(_cache))
    _cache = {}
    it3 = timeit.timeit(
        "test_stat_attatch()",
        "from __main__ import test_stat_attatch",
        number=100000
    )
    print("test_stat_attatch take:", it3)
    print("cache len:", len(_cache))
    


if __name__ == "__main__":
    main()
